<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类ID" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入分类ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleAdd"
        >上传文档</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 文档列表 -->
    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件ID" align="center" prop="fileId" width="200" />
      <el-table-column label="文件名" align="center" prop="fileName" :show-overflow-tooltip="true" />
      <el-table-column label="文件类型" align="center" prop="fileType" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'PARSE_SUCCESS'" type="success">解析成功</el-tag>
          <el-tag v-else-if="scope.row.status === 'PARSING'" type="warning">解析中</el-tag>
          <el-tag v-else-if="scope.row.status === 'PARSE_FAILED'" type="danger">解析失败</el-tag>
          <el-tag v-else type="info">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="sizeInBytes">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.sizeInBytes) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类ID" align="center" prop="categoryId" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateTags(scope.row)"
          >标签</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 上传文档对话框 -->
    <el-dialog title="上传文档" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入分类ID" />
        </el-form-item>
        <el-form-item label="文件上传" prop="file">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".pdf,.doc,.docx,.txt,.md"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf/doc/docx/txt/md文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="解析器" prop="parser">
          <el-select v-model="form.parser" placeholder="请选择解析器">
            <el-option label="DASHSCOPE_DOCMIND" value="DASHSCOPE_DOCMIND" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文档详情对话框 -->
    <el-dialog title="文档详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="文件ID">{{ detailForm.fileId }}</el-descriptions-item>
        <el-descriptions-item label="文件名">{{ detailForm.fileName }}</el-descriptions-item>
        <el-descriptions-item label="原始文件名">{{ detailForm.originalName }}</el-descriptions-item>
        <el-descriptions-item label="文件类型">{{ detailForm.fileType }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailForm.status }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">{{ formatFileSize(detailForm.sizeInBytes) }}</el-descriptions-item>
        <el-descriptions-item label="分类ID">{{ detailForm.categoryId }}</el-descriptions-item>
        <el-descriptions-item label="知识库ID">{{ detailForm.knowledgeBaseId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" v-if="detailForm.errorMessage" :span="2">
          <el-tag type="danger">{{ detailForm.errorMessage }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 标签编辑对话框 -->
    <el-dialog title="编辑标签" :visible.sync="tagsOpen" width="500px" append-to-body>
      <el-form ref="tagsForm" :model="tagsForm" label-width="80px">
        <el-form-item label="文档标签">
          <el-tag
            v-for="tag in tagsForm.tags"
            :key="tag"
            closable
            @close="handleTagClose(tag)"
            style="margin-right: 10px; margin-bottom: 10px;"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            size="small"
            style="width: 100px;"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTags">确 定</el-button>
        <el-button @click="tagsOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDocument, getDocument, delDocument, addDocument, delDocumentBatch, updateDocumentTags } from "@/api/ai"

export default {
  name: "Document",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      documentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 是否显示标签编辑弹出层
      tagsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        fileName: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 标签表单参数
      tagsForm: {
        fileId: null,
        tags: []
      },
      // 文件列表
      fileList: [],
      // 标签输入
      inputVisible: false,
      inputValue: '',
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "分类ID不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询文档列表 */
    getList() {
      this.loading = true
      listDocument(this.queryParams).then(response => {
        this.documentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        parser: "DASHSCOPE_DOCMIND"
      }
      this.fileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "上传文档"
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const fileId = row.fileId
      getDocument(fileId).then(response => {
        this.detailForm = response.data
        this.detailOpen = true
      })
    },
    /** 标签编辑按钮操作 */
    handleUpdateTags(row) {
      this.tagsForm.fileId = row.fileId
      this.tagsForm.tags = row.tags || []
      this.tagsOpen = true
    },
    /** 文件上传超出限制 */
    handleExceed() {
      this.$modal.msgError('只能选择一个文件')
    },
    /** 上传前校验 */
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$modal.msgError('上传文件大小不能超过 10MB!')
      }
      return isLt10M
    },
    /** 自定义上传 */
    handleUpload(param) {
      this.fileList = [param.file]
    },
    /** 提交上传 */
    submitUpload() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$modal.msgError("请选择要上传的文件")
            return
          }
          
          const formData = new FormData()
          formData.append('file', this.fileList[0])
          formData.append('categoryId', this.form.categoryId)
          formData.append('parser', this.form.parser)
          
          addDocument(formData).then(response => {
            this.$modal.msgSuccess("上传成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids
      this.$modal.confirm('是否确认删除文档编号为"' + fileIds + '"的数据项？').then(function() {
        return delDocument(fileIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
    },
    /** 标签相关方法 */
    handleTagClose(tag) {
      this.tagsForm.tags.splice(this.tagsForm.tags.indexOf(tag), 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.tagsForm.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    /** 提交标签 */
    submitTags() {
      updateDocumentTags(this.tagsForm.fileId, this.tagsForm.tags).then(response => {
        this.$modal.msgSuccess("标签更新成功")
        this.tagsOpen = false
        this.getList()
      })
    }
  }
}
</script>